﻿#include "server.h"
#include <QFile>
#include <QDebug>

http_sync_handler handler = [](HttpRequest* req, HttpResponse* resp)->int
{
    
    string path = req->path;    //获取请求的路径
    string host = req->GetHeader("Host");    //请求的Host
    QString qhost = QString::fromStdString(host);
    if(qhost.indexOf("minecraft.net") == -1 && qhost.indexOf("mojang.com")==-1)
    {
        
        host = "launchermeta.mojang.com";
    }
    string url = "http://"+host+path;      //请求的url
    
    qDebug()<<"path :"<<QString::fromStdString(path);
    string info = path +"\n"+ host+"\n"+url;
    
    resp->headers["content-type"] = "text/plain;charset=utf-8";
    
    

    Library *lb = Library::getInstance();
    CFile cfile = lb->get(QString::fromStdString(url));
    if(cfile.size <=0)
    {
        string result = "minecraft资源处于繁忙状态，请稍后重试或者更换官方源  "+info;
        resp->body = result;
        return result.size();
    }
    //表明二进制数据
    resp->headers["Content-Type"] = "application/octet-stream";
    
    //告诉大小是多少
    resp->headers["Content-Length"] = QString::number(cfile.size).toStdString();
    resp->Data(cfile.data,cfile.size);
    
    return cfile.size;
};

Server::Server()
{
    qDebug() << "server init";
    
}

void Server::start(int port)
{
    
    route.GET("*",handler);
    server.port = port;
    //server.host = "0.0"
    server.service = &route;
    
    http_server_run(&server);
}

void Server::stop()
{
    http_server_stop(&server);
}
